package cn.itcast.sys.service.impl;

import cn.itcast.constant.*;
import cn.itcast.context.BaseContext;
import cn.itcast.exception.AccountFreezeException;
import cn.itcast.exception.AccountLockedException;
import cn.itcast.exception.AccountNotFoundException;
import cn.itcast.exception.PasswordErrorException;
import cn.itcast.properties.JwtProperties;
import cn.itcast.result.PageBean;
import cn.itcast.sys.dto.EmployeeDTO;
import cn.itcast.sys.dto.EmployeeLoginDTO;
import cn.itcast.sys.dto.EmployeePageQueryDTO;
import cn.itcast.sys.dto.PasswordEditDTO;
import cn.itcast.sys.mapper.EmployeeMapper;
import cn.itcast.sys.pojo.Employee;
import cn.itcast.sys.service.EmployeeService;
import cn.itcast.sys.vo.EmployeeLoginVO;
import cn.itcast.utils.JwtUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        // 判断账号是否在冻结期间
        if (redisTemplate.hasKey(username) && "string".equals(redisTemplate.type(RedisConstant.ACCOUNT_LOGIN_INFO + username).code())) {
            throw new AccountFreezeException(MessageConstant.ACCOUNT_FREEZE + ",冻结时间剩余" +
                    redisTemplate.getExpire(username, TimeUnit.MINUTES) + "分"
                    + ((redisTemplate.getExpire(username) % 60)) + "秒");
        }

        // 根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        // 处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        if (!BCrypt.checkpw(password, employee.getPassword())) {
            // 密码错误

            // 一分钟之内，密码连续输错三次，账号冻结一小时
            redisTemplate.opsForList().rightPush(RedisConstant.ACCOUNT_LOGIN_INFO + username, System.currentTimeMillis());

            // 超过一分钟未登录错误，则抹除登录错误记录释放空间
            redisTemplate.expire(RedisConstant.ACCOUNT_LOGIN_INFO + username, 1, TimeUnit.MINUTES);

            // 清除不在时间窗口内的登录记录
            while (((long) redisTemplate.opsForList().index(RedisConstant.ACCOUNT_LOGIN_INFO + username, 0)) < (System.currentTimeMillis() - 60000)) {
                redisTemplate.opsForList().leftPop(RedisConstant.ACCOUNT_LOGIN_INFO + username);
            }

            // 判断时间窗口内登录次数

            if (redisTemplate.opsForList().size(RedisConstant.ACCOUNT_LOGIN_INFO + username) >= 3) {
                redisTemplate.delete(RedisConstant.ACCOUNT_LOGIN_INFO + username);
                redisTemplate.opsForValue().set(RedisConstant.ACCOUNT_LOGIN_INFO + username, "freeze", 1, TimeUnit.HOURS);
                throw new PasswordErrorException("密码已连续输错三次！账号冻结一小时！");
            }

            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        // 密码输入正确，删除累计登录错误信息
        redisTemplate.delete(RedisConstant.ACCOUNT_LOGIN_INFO + employee.getUsername());


        if (employee.getStatus() == StatusConstant.DISABLE) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }


        // 登陆成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        claims.put(JwtClaimsConstant.USERNAME, employee.getUsername());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        // 返回实体对象
        return employeeLoginVO;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    @SneakyThrows
    public void save(EmployeeDTO employeeDTO) {

        Employee employee = new Employee();
        // 对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        // 设置账号状态，默认状态 1 表示正常 0 表示锁定
        employee.setStatus(StatusConstant.ENABLE);



        // 设置初始密码
        employee.setPassword(BCrypt.hashpw(PasswordConstant.DEFAULT_PASSWORD, BCrypt.gensalt()));


        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageBean pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {

        // 开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        return new PageBean(page.getTotal(), page.getResult());

    }

    /**
     * 启用禁用员工账号
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .build();
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);

        employee.setPassword("****");

        return employee;

    }

    /**
     * 编辑员工信息
     *
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        employeeMapper.update(employee);
    }

    /**
     * 修改密码
     *
     * @param passwordEditDTO
     */
    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        String oldPassword = employeeMapper.getById(BaseContext.getCurrentId()).getPassword();

        if (!BCrypt.checkpw(passwordEditDTO.getOldPassword(), oldPassword)) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED + ",旧密码错误！");
        }


        if (BCrypt.checkpw(passwordEditDTO.getNewPassword(), oldPassword)) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED + ",新密码不能于旧密码相同！");
        }


        Employee employee = Employee.builder()
                .id(BaseContext.getCurrentId())
                .password(BCrypt.hashpw(passwordEditDTO.getNewPassword(), BCrypt.gensalt()))
                .build();

        employeeMapper.update(employee);
    }

    /**
     * 根据id查询账号所有权限
     *
     * @param id
     * @return
     */
    @Override
    public Set<String> selectMenuPermsByEmployeeId(Long id) {

        Set<String> perms = employeeMapper.selectMenuPermsByUserId(id);
//        Set<String> permsSet = new HashSet<>();
//        for (String perm : perms) {
//            if (perm != null) {
//                permsSet.add(perm);
//            }
//        }
        return perms;
    }

    /**
     * 将员工信息导出为Excel报表接口
     *
     * @param response
     */
    @SneakyThrows
    @Override
    public void exportEmployee(HttpServletResponse response) {
        List<Employee> list = employeeMapper.pageQuery(new EmployeePageQueryDTO());

        InputStream is = this.getClass().getClassLoader().getResourceAsStream("templates/employee员工.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(is);
        XSSFSheet sheet = excel.getSheetAt(0);

        for (int i = 0; i < list.size(); i++) {
            Employee employee = list.get(i);
            XSSFRow row = sheet.getRow(i + 1);
            if (row == null) row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(employee.getId());
            row.createCell(1).setCellValue(employee.getUsername());
            row.createCell(2).setCellValue(employee.getName());
            row.createCell(3).setCellValue(employee.getPassword());
            row.createCell(4).setCellValue(employee.getPhone());
            row.createCell(5).setCellValue(employee.getSex());
            row.createCell(6).setCellValue(employee.getIdNumber());
            row.createCell(7).setCellValue(employee.getStatus());
            row.createCell(8).setCellValue(employee.getCreateTime().toString());
            row.createCell(9).setCellValue(employee.getUpdateTime().toString());
            row.createCell(10).setCellValue(employee.getCreateUser());
            row.createCell(11).setCellValue(employee.getUpdateUser());
        }

        ServletOutputStream os = response.getOutputStream();
        excel.write(os);

        os.flush();
        os.close();
        excel.close();
    }

}
